﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

using Microsoft.Web.WebView2.Core;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Popups;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace uwp_sample
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        Microsoft.Web.WebView2.Core.CoreWebView2 WebView;

        public MainPage()
        {
            this.InitializeComponent();
            InitializeCoreWebView2();
        }
        private async void WebView2_NavigationStarting(CoreWebView2 sender, CoreWebView2NavigationStartingEventArgs args)
        {
            string profileName = WebView.Profile.ProfileName;
            bool isInPrivateModeEnabled = WebView.Profile.IsInPrivateModeEnabled;
            MessageDialog dialog = new MessageDialog($"profile name = {profileName}, private mode = {isInPrivateModeEnabled}");
            await dialog.ShowAsync();
        }

        public async Task InitializeCoreWebView2()
        {
            Environment.SetEnvironmentVariable("COREWEBVIEW2_FORCED_HOSTING_MODE", "COREWEBVIEW2_HOSTING_MODE_WINDOW_TO_VISUAL");

            CoreWindow coreWindow = Windows.UI.Core.CoreWindow.GetForCurrentThread();
            CoreWebView2Environment env = await CoreWebView2Environment.CreateAsync();
            CoreWebView2ControllerWindowReference windowReference = CoreWebView2ControllerWindowReference.CreateFromCoreWindow(coreWindow);
            CoreWebView2ControllerOptions options = env.CreateCoreWebView2ControllerOptions();
            options.ProfileName = "profile_uwp";
            options.IsInPrivateModeEnabled = true;
            CoreWebView2Controller controller = await env.CreateCoreWebView2ControllerAsync(windowReference, options);
            WebView = controller.CoreWebView2;

            WebView.NavigationStarting += WebView2_NavigationStarting;
            WebView.Navigate("https://www.bing.com");
        }
    }
}
